<!--
* @author: XJC
* @date: 2023-11-27 10:14
* @description：出入库记录-用户端
* @update: 2023-11-27 10:14
-->
<template>
  <div class="container">
    <div class="app-container">
      <div class="radioBox" v-if="isLogin">
        <el-radio-group v-model="flag" size="medium">
          <el-radio-button :label="false"> 全部出入库记录 </el-radio-button>
          <el-radio-button :label="true"> 我的出入库记录 </el-radio-button>
        </el-radio-group>
      </div>
      <div class="contentBox">
        <div class="inventory-top form-top">
          <el-form ref="historyForm" :model="historyForm" label-width="110px">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="物料名称">
                  <el-select
                    filterable
                    style="width: 100%"
                    v-model="historyForm.goodsName"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in materialName"
                      :key="index"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="规格型号">
                  <el-select
                    filterable
                    style="width: 100%"
                    v-model="historyForm.goodsModel"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in standardsList"
                      :key="index"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="货架名称">
                  <el-select
                    filterable
                    style="width: 100%"
                    v-model="historyForm.shelvesName"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in goodsShelves"
                      :key="index"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="关键字">
                  <el-input
                    style="width: 100%"
                    v-model.trim="historyForm.keyWord"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="出入库类型">
                  <el-select
                    filterable
                    style="width: 100%"
                    v-model="historyForm.type"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in libraryType"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" style="text-align: right">
                <el-button class="chamfer-98" type="primary" @click="searchBtn"
                  >查询</el-button
                >
                <el-button class="chamfer-98" plain @click="resetBtn"
                  >重置</el-button
                >
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="inventory-bot table-normal">
          <div class="btnBox" style="text-align: right">
            <el-button type="primary" class="chamfer-98" @click="associateTaskBtn">
              <span class="btn-middle">
                <span>任务</span>
                <img class="btn-icon" src="~@/assets/material_img/addBtn.png" />
              </span>
            </el-button>
            <el-button type="primary" class="chamfer-98" @click="exportBtn">
              <span class="btn-middle">
                <span>导出</span>
                <img
                  class="btn-icon"
                  src="~@/assets/material_img/exportBtn.png"
                />
              </span>
            </el-button>
          </div>
          <el-table
            v-loading="loading"
            element-loading-background="rgba(0, 0, 0, 0.6)"
            ref="multipleTable"
            :data="historyTable"
            fit
            style="width: 100%"
            header-row-class-name="tableHeader"
            header-cell-class-name="tableTrHeader"
            row-class-name="tableRow"
            cell-class-name="tableCell"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              align="center"
              type="selection"
              width="80"
              label-class-name="DisabledSelection"
            />
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            />
            <el-table-column
              prop="goodsName"
              label="物料名称"
              width="110"
              :show-overflow-tooltip="true"
              align="center"
            />
            <el-table-column
              prop="goodsModel"
              label="规格型号"
              width="120"
              align="center"
            />
            <el-table-column
              prop="shelvesName"
              label="货架名称"
              align="center"
              width="140"
            />
            <el-table-column
              prop="positionName"
              label="库位号"
              width="100"
              align="center"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.layerSort }} - {{scope.row.positionName}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="type"
              label="出入库类型"
              align="center"
              width="110"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.type === 0">未知</span>
                <span v-if="scope.row.type === 1">出库</span>
                <span v-if="scope.row.type === 2">入库</span>
              </template>
            </el-table-column>
            <el-table-column prop="realCount" label="数量" align="center" />
            <el-table-column
              prop="taskName"
              label="任务名称"
              :show-overflow-tooltip="true"
              align="center"
              width="140"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.taskName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateBy"
              label="操作人"
              align="center"
              width="100"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.nickName || '默认用户' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="操作时间"
              align="center"
              width="200"
            />
          </el-table>
          <!-- 分页 -->
          <paging-component
            :total="total"
            :page-size="historyForm.currentSize"
            :current-page="historyForm.currentPage"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 关联任务弹窗 -->
    <el-dialog
      append-to-body
      title="关联任务" :visible.sync="dialogVisible" width="30%"
               custom-class="my-dialog hardConfig"
               center
    >
      <el-form :model="taskForm" ref="taskForm" label-width="80px">
        <el-form-item label="任务名称" prop="taskName" :rules="[{ required: true, message: '请输入关联任务名称', trigger: 'blur' }]">
          <el-input v-model="taskForm.taskName" placeholder="请输入关联任务名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAssociateTask">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getMaterialNameList, getMaterialModelList } from '@/api/materialManage'
import {
  getHistoryInventoryList,
  exportGoodsInoutRecordExcelApi,
  getGoodsShelvesInfoList,
  associateTaskApi
} from '@/api/inventoryManage'
import pagingComponent from '@/components/PagingComponent/index.vue'
import { mapGetters } from 'vuex'
export default {
  components: { pagingComponent },
  data() {
    return {
      flag: false, // 切换
      // 历史库存记录表单
      historyForm: {
        goodsName: '', // 物料名称
        goodsModel: '', // 规格型号
        shelvesName: '', // 货架名称
        keyWord: '', // 关键字
        type: '', // 出入库类型
        currentPage: 1, // 页码
        currentSize: 20, // 页尺寸
        isMe: false // 是否是我的任务
      },
      total: 0, // 历史库存记录总数
      multipleSelection: [], // 表格勾选数据
      // 物料名称
      materialName: [],
      // 规格型号
      standardsList: [],
      // 货架名称
      goodsShelves: [],
      // 出入库类型
      libraryType: [
        {
          value: 0,
          name: '未知'
        },
        {
          value: 1,
          name: '出库'
        },
        {
          value: 2,
          name: '入库'
        }
      ],
      // 历史库存记录列表
      historyTable: [],
      loading: false,
      dialogVisible: false, // 关联任务弹窗显示状态
      taskForm: {
        taskName: '', // 关联任务名称
        ids: [] // 选中的记录ID
      }
    }
  },
  created() {
    this.renderList()
  },
  computed: {
    ...mapGetters(['isLogin'])
  },
  watch: {
    isLogin(val) {
      if (!val) {
        this.flag = false
      }
    },
    flag(val) {
      if (val) {
        this.historyForm = {
          goodsName: '',
          goodsModel: '',
          shelvesName: '',
          keyWord: '',
          type: '',
          currentPage: 1,
          currentSize: 20,
          isMe: true
        }
        this.renderList()
      } else {
        this.historyForm = {
          goodsName: '',
          goodsModel: '',
          shelvesName: '',
          keyWord: '',
          type: '',
          currentPage: 1,
          currentSize: 20,
          isMe: false
        }
        this.renderList()
      }
    }
  },

  methods: {
    // 切换
    switchChange(val) {
      this.flag = val
    },
    // 获取列表
    async renderList() {
      this.loading = true
      const { result } = await getHistoryInventoryList(this.historyForm)
      this.total = Number(result.totalCount)
      this.historyTable = result.currentData
      // 更新下拉菜单数据
      let { result: list1 } = await getMaterialNameList()
      this.materialName = list1
      let { result: list2 } = await getMaterialModelList()
      this.standardsList = list2
      let { result: list3 } = await getGoodsShelvesInfoList()
      this.goodsShelves = list3
      this.loading = false
    },
    // 查询
    searchBtn() {
      this.historyForm.currentPage = 1
      this.renderList()
    },
    // 重置
    resetBtn() {
      this.historyForm = {
        goodsName: '', // 物料名称
        goodsModel: '', // 规格型号
        shelvesName: '', // 货架名称
        keyWord: '', // 关键字
        type: '', // 出入库类型
        currentPage: 1, // 页码
        currentSize: 20, // 页尺寸
      }
      if (this.flag) {
        this.historyForm.isMe = true
      } else {
        this.historyForm.isMe = false
      }
      this.renderList()
    },
    // pageSize改变时会触发(每页数据条数)
    handleSizeChange(val) {
      this.historyForm.currentSize = val
      this.renderList()
    },
    // currentPage改变时会触发(当前页码数)
    handleCurrentChange(val) {
      this.historyForm.currentPage = val
      this.renderList()
    },
    // 导出
    async exportBtn() {
      if (this.multipleSelection.length > 0) {
        // 创建一个数组，里面存勾选数据的id
        let delArrayData = []
        this.multipleSelection.forEach((item) => {
          delArrayData.push(item.id)
        })
        await exportGoodsInoutRecordExcelApi({ ids: delArrayData })
          .then((result) => {
            if (result.size <= 10) {
              this.$message({
                type: 'error',
                message: '导出失败!'
              })
              return
            }
            const content = result
            const blob = new Blob([content], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }) //处理返回
            const fileName = '出入库信息.xlsx'
            if ('download' in document.createElement('a')) {
              // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
          })
          .catch((err) => {
            this.$message({
              type: 'error',
              message: '导出失败!'
            })
          })
      } else {
        await exportGoodsInoutRecordExcelApi(this.historyForm)
          .then((result) => {
            if (result.size <= 10) {
              this.$message({
                type: 'error',
                message: '导出失败!'
              })
              return
            }
            const content = result
            const blob = new Blob([content], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }) //处理返回
            const fileName = '出入库信息.xlsx'
            if ('download' in document.createElement('a')) {
              // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
          })
          .catch((err) => {
            this.$message({
              type: 'error',
              message: '导出失败!'
            })
          })
      }
    },

    associateTaskBtn() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一条记录进行关联！'
        })
        return
      }
      this.dialogVisible = true
      this.taskForm.taskName = ''
    },

    // 确认关联任务
    async confirmAssociateTask() {
      this.$refs.taskForm.validate(async (valid) => {
        if (valid) {
          // 获取选中记录的ID
          const ids = this.multipleSelection.map(item => item.id)

          try {
            this.loading = true
            // 调用后端API关联任务
            // 这里需要根据实际后端API来实现
            await associateTaskApi({
              taskName: this.taskForm.taskName,
              ids: ids
            })

            this.$message({
              type: 'success',
              message: '关联任务成功！'
            })
            this.dialogVisible = false
            this.renderList() // 刷新列表
          } catch (error) {
            this.$message({
              type: 'error',
              message: '关联任务失败：' + (error.message || '未知错误')
            })
          } finally {
            this.loading = false
          }
        }
      })
    },
    // 获取勾选数据表格
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>
<style lang="scss">
@import '~@/styles/_handle.scss';

.is-active {
  .el-radio-button__inner {
    @include background('radio_bg_active');
  }
}
.el-radio-button__inner {
  @include background('radio_bg');
}
.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  @include background('table_hover_color');
}
</style>
<style scoped lang="scss">
@import '~@/styles/_handle.scss';
::v-deep .radioBox {
  text-align: center;
  .el-radio-button:first-child {
    .el-radio-button__inner {
      border: none;
      margin-right: -16px;
    }
  }
  .is-active {
    .el-radio-button__inner {
      border: none;
      box-shadow: none;
    }
  }
  .el-radio-button__inner {
    width: 188px;
    height: 54px;
    border: none;
    line-height: 36px;
    font-size: 20px;
    box-shadow: none;
    color: rgba($color: #fff, $alpha: 0.8);
  }
}
.container{
  height: 100%;
  .app-container{
    height: calc(100% - 50px);
  }
}

::v-deep .el-form-item__label {
  color: white !important;
}

::v-deep .hardConfig {
  .el-form-item__label {
    color: white !important;
  }
}
.contentBox {
  height: calc(100% - 50px);
  border: 1px solid;
  @include border_image('container_border');
  @include background('content_bg_color');
}
.inventory-top {
  @include background('table_head_bgcolor');
}
::v-deep .contentBox {
  width: 1016px;
  padding: 32px 17px 0;
  margin: 0 auto;
  border-radius: 10px;
  .inventory-top {
    padding: 20px;
    width: 982px;
    height: 141px;
    border-radius: 10px;
    .el-form-item {
      margin-bottom: 16px;
    }
    .chamfer-98 {
      font-size: 18px;
    }
  }
  .inventory-bot {
    height: calc(100% - 141px);
    padding: 20px 10px;
    .btnBox {
      height: 44px;
      .chamfer-98 {
        font-size: 18px;
        text-align: center;
        .btn-middle {
          display: flex;
          align-items: center;
          .btn-icon {
            margin-left: 4px;
            width: 16px;
            height: 16px;
          }
        }
      }
    }
    .el-table {
      height: calc(100% - 130px);
      // 表格全选框去除空框
      .DisabledSelection .cell .el-checkbox__inner {
        display: none;
        position: relative;
      }
      .el-table__body-wrapper{
        height: calc(100% - 48px);
        overflow-y: auto;
      }
      .el-table__body-wrapper::-webkit-scrollbar{
        width: 6px;
        height: 8px;
      }
      .tableTrHeader {
        border: none;
      }
    }
  }
}

// 取消表格底部横线
::v-deep .el-table--border::after,
.el-table--group::after,
.el-table::before {
  content: none;
}
</style>
